package com.twt.sys.controller;

import com.twt.sys.interceptor.LoginContext;
import com.twt.sys.interceptor.NotLoginException;
import com.twt.model.system.entity.SysUser;
import com.twt.sys.base.BaseController;
import com.twt.common.pojo.Result;
import com.twt.common.pojo.ResultCodeEnum;
import com.twt.model.base.SysConsts;
import com.twt.sys.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@RestController
public class LoginController {
    // 这些对象何以直接被子类使用
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest req, HttpServletResponse res) {
        this.request = req;
        this.response = res;
        this.session = req.getSession();
    }
    @Value("${project.isDev}")
    private Boolean isDev;

    @Qualifier(value = "loginServiceImpl")
    @Autowired
    private LoginService loginService;

    @GetMapping("/login")
    public Result login(SysUser sysUser) {
        if (sysUser == null) {
            return Result.fail(ResultCodeEnum.ACC_PWD_WRONG);
        }
        SysUser loginUser = loginService.login(sysUser);
        if (loginUser != null) {
            LoginContext.INSTANCE.addSessionId(session.getId());
            session.setAttribute(SysConsts.SYSUSER_KEY, loginUser);
            return Result.ok(loginUser);
        }
        return Result.fail(ResultCodeEnum.ACC_PWD_WRONG);
    }

    @PostMapping("/logout")
    public Result logout() {
        LoginContext.INSTANCE.removeSessionId(session.getId());
        return Result.ok();
    }


    @GetMapping("/dev/login")
    public Result devLogin(SysUser sysUser) {
        if (isDev == null || !isDev) {
            throw new NotLoginException();
        }
        SysUser loginUser = new SysUser();
        loginUser.setAccount("admin");
        loginUser.setPassword("admin");
        if (loginUser.getAccount().equals(sysUser.getAccount()) && loginUser.getPassword().equals(sysUser.getPassword())) {
            LoginContext.INSTANCE.addSessionId(session.getId());
            session.setAttribute(SysConsts.SYSUSER_KEY, loginUser);
            return Result.ok();
        }
        return Result.fail(ResultCodeEnum.ACC_PWD_WRONG);
    }
}
